﻿//for configuration of hierarchy tab
//for Hierarchy sub-tab
var hier_id;
var vers_id;

var hier_name;
var is_published;
var isNodeType = false;
var tempNodeTypeId = new Array();
tempNodeTypeId[0] = -1;
var HierGridSelId = -1;
var node_type_id;
var attr_precision;

function BindVersionCombo(opr, id, comboid, tab, addTblName) {
    //debugger
    var page = "ConfigHierCallback.aspx";

    $.ajax({
        async: false,
        type: 'POST',
        url: page + "?operation=" + opr + "&id=" + id,
        success: function (str) {
            var data = eval('(' + str + ')');

            $("#" + comboid).empty();
            $("#tmplOptions").tmpl(data).appendTo("#" + comboid);

            $("#" + comboid + " option").each(function (i) {
                //debugger;
                $(this).data("IS_PUBLISHED", data[i].is_published);
            });
        }
    });
}


function loadHierarchy() {
    // debugger;
    var url = "ConfigHierCallback.aspx?operation=get_HierarchyData";

    $.ajax({
        async: true,
        type: 'GET',
        url: "ConfigHierCallback.aspx?operation=get_HierarchyColumns",
        data: "",
        dataType: "json",
        success: function (result) {
            //debugger;
            $("#dtHier").GridUnload(); // destroy the grid saving the table and pager
            var editurl = "table=X_HIERARCHIES";

            //call fill grid for dimension table          
            fillgridHierNav(result, "#dtHier", "#pgHier", "800", "350px", "Hierarchy Data", editurl, url);

        },
        error: function (x, e) {
            //debugger
            alert(x.readyState + " " + x.status + " " + e.msg);
        }
    });
}



//to fill jqgird - function with Add , Edit and Delete for dimension 
function fillgridHierNav(result, tblname, pgname, gWidth, gHeight, caption, editurll, url) {

    //debugger;
    var colN = result.columns, colM = result.colModelList;

    jQuery(tblname).jqGrid({
        // data: colD,
        // datatype: 'local',
        url: url,
        datatype: 'json',
        gridview: true,
        colNames: colN,
        colModel: colM,
        caption: caption,
        editurl: "ConfigHierCallback.aspx?" + editurll,
        rowNum: 10,
        pager: pgname,
        sortname: result.primarykey,
        sortorder: "desc",
        width: "800px",
        height: "100%",
        scrollOffset: 18,
        closeAfterEdit: true,
        ignoreCase: true,
        viewrecords: true,
        loadComplete: function (data) {
            //debugger;
            if (tblname == "#dtNodeType") {
                jQuery(tblname).setGridWidth("550", true);
                //disable delete button
                if (is_published == true) {
                    $("#del_dtNodeType").addClass('ui-state-disabled');
                }
                else {
                    $("#del_dtNodeType").removeClass('ui-state-disabled');
                }

                var dataType = "nvarchar:nvarchar;varchar:varchar;float:float;int:int;bigint:bigint;datetime:datetime;char:char";
                var appendtagPrec = "<font id='fprec' style='font-weight: bold; color: #FF0000; vertical-align: bottom;'>*</font>";

                $(tblname).setColProp('ATTR_DATA_TYPE', {
                    editoptions: { "style": "width:160px",
                        "size": 400,
                        value: dataType,
                        dataEvents: [{ type: 'change',
                            fn: function (e) {
                                var val = $(e.target).val();
                                var relTo = $("#ATTR_PRECISION", "#FrmGrid_dtNodeType");
                                //debugger;
                                if (val == "float" || val == "int" || val == "datetime" || val == "bigint") {
                                    $("#dtNodeType").setColProp('ATTR_PRECISION', { editrules: { required: false} });
                                    $('#fprec', '#FrmGrid_dtNodeType').remove();
                                }
                                else {
                                    $("#dtNodeType").setColProp('ATTR_PRECISION', { editrules: { required: true} });
                                    $('#fprec', '#FrmGrid_dtNodeType').remove();
                                    $(appendtagPrec).insertAfter(relTo);
                                }
                            }
                        }]
                    }
                });

            }
            else {
                jQuery(tblname).setGridWidth("900", true);
            }
        },
        onSelectRow: function (rowid) {
            var IsPublished;
            //debugger;

            //if _xref ,_grey tables exist disable delete button else
            //enable table
            if (tblname == "#dtHier") {

                IsPublished = $(this).jqGrid('getCell', rowid, 'IS_PUBLISHED');
                var HasVersion = $(this).jqGrid('getCell', rowid, 'HAS_VERSION');

                if (IsPublished == "1" || HasVersion == "1") {
                    //alert("Related Tables exists ! Can't Delete Table !");
                    $("#del_" + this.id).addClass('ui-state-disabled');
                }
                else {
                    $("#del_" + this.id).removeClass('ui-state-disabled');
                }
            }
            else if (tblname == "#dtVer") {

                IsPublished = $(this).jqGrid('getCell', rowid, 'VERSION_STATUS');
                IsPublished = IsPublished.toString().toLowerCase();

                if (IsPublished == "published") {
                    //alert("Related Tables exists ! Can't Delete Table !");
                    $("#del_" + this.id).addClass('ui-state-disabled');
                }
                else {
                    $("#del_" + this.id).removeClass('ui-state-disabled');
                }
            }

            return true;

        },
        loadError: function (xhr, status, error) {
            ////debugger;
            alert('error');
        }
    });

    //navigation grid setting
    navGridHier(tblname, pgname);
}


//navigation bar of grid- setting metohd
function navGridHier(tblname, pgname) {
    // debugger;
    var tblrowid;

    jQuery(tblname).jqGrid('navGrid', pgname, { del: true, edit: true, add: true, search: true },
   {
       //edit
       afterSubmit: afterSubCommon,
       closeAfterEdit: true,
       reloadAfterSubmit: true,
       width: "500",
       modal: true,
       onInitializeForm: function (formid) {
           // //debugger;         
           //for  * sign for mandatory field  and datepicker
           colModelLocal = $(".ui-jqgrid-btable").get(0).p.colModel;
           var arr = tblname.split('#');
           colModelLocal = $("table[id=" + arr[1] + "]").get(0).p.colModel;

           //common method for suffice star in add/edit dialog box
           SufficeStarHier(colModelLocal, formid, "edit");
       },
       beforeSubmit: function (postdata, formid) {
           //debugger;
           if (tblname == "#dtNodeType") {
               if (parseInt(postdata["ATTR_PRECISION"]) < parseInt(attr_precision)) {//parseInt("50")< parseInt("100")
                   alert("Precision cannot be smaller !");
                   return false;
               }
               else {
                   return [true, '', ''];
               }
           }
           else {
               return [true, '', ''];
           }
       },
       afterComplete: function (response, postdata, formid) {
           // debugger;
           if (tblname == "#dtNodeType") {
               var attr_id = response.responseText;
               jQuery("#dtNodeType").jqGrid('setCell', attr_id, 'HIERARCHY_ID', hier_id, "");
               jQuery("#dtNodeType").jqGrid('setCell', attr_id, 'VERSION_ID', vers_id, "");
               jQuery("#dtNodeType").jqGrid('setCell', attr_id, 'NODE_TYPE_ID', node_type_id, "");
           }
       },
       beforeSubmit: function (posdata, formid) {
           //debugger;
           if (tblname == "#dtVer") {
               //debugger;
               var rowidVer = $("#dtVer").jqGrid('getGridParam', 'selrow');

               var reccnt = $("#dtVer").getGridParam("reccount") + 1;
               if (reccnt > 1) {
                   var stdate = posdata['START_DATE'];
                   var enddate = posdata['END_DATE'];

                   var enddates = jQuery("#dtVer").jqGrid('getCol', 'END_DATE', false, '');
                   var startdates = jQuery("#dtVer").jqGrid('getCol', 'START_DATE', false, '');
                   var Ids = jQuery("#dtVer").jqGrid('getCol', 'ID', false, '');

                   for (var i = 0; i < enddates.length; i++) {
                       if (rowidVer != Math.floor(Ids[i])) {

                           var arrEdata = enddates[i].split('/');
                           var dtE = new Date(arrEdata[2] + "/" + arrEdata[0] + "/" + arrEdata[1]);

                           var arrSdata = startdates[i].split('/');
                           var dtS = new Date(arrSdata[2] + "/" + arrSdata[0] + "/" + arrSdata[1]);

                           //Testing the range "start1 to end1" against the range "start2 to end2" is done by testing if... 
                           // ( start1 <= end2 and start2 <= end1 )

                           // if (!((new Date(stdate) > dtE || new Date(stdate) < dtS) && (new Date(enddate) > dtE || new Date(enddate) < dtS))) {
                           if ((new Date(stdate) <= dtE) && (dtS <= new Date(enddate))) {
                               alert("Date range is overlapping ");
                               return false;
                           }
                       }
                   }

                   return [true, '', ''];
               }
           }
       },
       beforeShowForm: function (formid) {
           //debugger;
           var tblrowid = jQuery("#dtHier").jqGrid('getGridParam', 'selrow');

           if (tblname == "#dtHier") {
               if (jQuery("#dtHier").jqGrid('getCell', tblrowid, 'IS_PUBLISHED') == "1") {
                   $('#HIER_ABBR_CODE', formid).attr("disabled", "disabled");
               }
               else {
                   $('#HIER_ABBR_CODE', formid).removeAttr("disabled");
               }
           }
           else if (tblname == "#dtVer") {
               if (jQuery("#dtVer").jqGrid('getCell', tblrowid, 'VERSION_STATUS').toString().toLowerCase() == "published") {
                   $('#START_DATE', formid).attr("disabled", "disabled");
                   $('#END_DATE', formid).attr("disabled", "disabled");
               }
               else {
                   $('#START_DATE', formid).removeAttr("disabled");
                   $('#END_DATE', formid).removeAttr("disabled");
               }

           }
           else if (tblname == "#dtNodeType") {
               //debugger;
               putstarForMAndatory();

               if (is_published == true) {

                   $('#ATTR_COLUMN', formid).attr("disabled", "disabled");
                   $('#ATTR_DATA_TYPE', formid).attr("disabled", "disabled");

                   //IS_PRIMARY
                   $('#DROPDOWN_VAL', formid).attr("disabled", "disabled");
                   $('#CONTROL_TYPE', formid).attr("disabled", "disabled");

                   attr_precision = $('#ATTR_PRECISION', formid).val();
               }
           }
           ////
       }
   },
   {//new
       afterSubmit: function (response) {
           //debugger;

           var arr = response.responseText.split("|");
           if (arr[0] == "false") {
               if (arr[1] != "") {
                   return [false, arr[1]]
               }
               else {
                   return [false, "some error in save !"]
               }
           }
           else {
               if (tblname == "#dtVer") {

                   var reccnt = $("#dtVer").getGridParam("reccount") + 1;
                   if (reccnt == 1) {
                       jQuery("#dtHier").jqGrid('setCell', HierGridSelId, 'HAS_VERSION', "1", "");
                       $("#del_dtHier").addClass('ui-state-disabled');
                   }
               }

               return [true, "saved successfully !", response.responseText]
           }
       },
       closeAfterAdd: true,
       reloadAfterSubmit: true,
       width: "500",
       modal: true,
       onInitializeForm: function (formid) {
           ////debugger;
           //for  * sign for mandatory field  and datepicker
           colModelLocal = $(".ui-jqgrid-btable").get(0).p.colModel;
           var arr = tblname.split('#');
           colModelLocal = $("table[id=" + arr[1] + "]").get(0).p.colModel;
           //common method for suffice star in add/edit dialog box
           SufficeStarHier(colModelLocal, formid, "new");
       },
       beforeShowForm: function (formid) {

           //debugger;
           var tblrowid = jQuery("#dtHier").jqGrid('getGridParam', 'selrow');
           if (tblname == "#dtHier") {
               if (jQuery("#dtHier").jqGrid('getCell', tblrowid, 'IS_PUBLISHED') == "1") {
                   $('#HIER_ABBR_CODE', formid).attr("disabled", "disabled");
               }
               else {
                   $('#HIER_ABBR_CODE', formid).removeAttr("disabled");
               }
           }
           else if (tblname == "#dtVer") {

               $('#START_DATE', formid).removeAttr("disabled");
               $('#END_DATE', formid).removeAttr("disabled");

           }
           else if (tblname == "#dtNodeType") {
               //debugger;
               putstarForMAndatory();
           }
       }
   },
   {//delete
       afterSubmit: function (response) {
           //debugger;
           if (response.responseText == "true") {
               return [true, "deleted successfully !"]
           }
           else if (response.responseText == "false") {
               return [false, "some error in delete !"]
           }
           else {
               var arr = response.responseText.split("|");
               return [false, arr[1]]
           }
       },
       closeAfterEdit: true,
       reloadAfterSubmit: false,
       beforeShowForm: function (formid) {
           //            debugger;
           //            tblrowid = jQuery("#dtHier").jqGrid('getGridParam', 'selrow');
           //            if (tblname == "#dtHier") {
           //                if (jQuery("#dtHier").jqGrid('getCell', tblrowid, 'HAS_VERSION') == "1") {
           //                    alert("Related Version exists ! First Delete Version Data. !");
           //                    return false;
           //                }
           //            }
       }
   },
    {//complex search
        multipleSearch: true,
        multipleGroup: true,
        showQuery: true
    }
);
}

function putstarForMAndatory(formid) {

    ///put mandatory editrule depending on condition             
    var relTo = $("#ATTR_PRECISION", formid);
    var appendtagPrec = "<font id='fprec' style='font-weight: bold; color: #FF0000; vertical-align: bottom;'>*</font>";
    var val = $('#ATTR_DATA_TYPE', formid).attr('value');
    if (val == "float" || val == "int" || val == "datetime" || val == "bigint") {
        $("#dtNodeType").setColProp('ATTR_PRECISION', { editrules: { required: false} });
        $('#fprec', '#FrmGrid_dtNodeType').remove();
    }
    else {
        $("#dtNodeType").setColProp('ATTR_PRECISION', { editrules: { required: true} });
        $('#fprec', '#FrmGrid_dtNodeType').remove();
        $(appendtagPrec).insertAfter(relTo);
    }
}

function loadVersion() {

    //debugger;
    if (hier_id != jQuery("#dtHier").jqGrid('getGridParam', 'selrow')) {

        HierGridSelId = jQuery("#dtHier").jqGrid('getGridParam', 'selrow');
        hier_id = Math.floor(jQuery("#dtHier").jqGrid('getCell', HierGridSelId, 'HIERARCHY_ID'));

        if (hier_id == null || hier_id == "undefined") {
            alert("Please Select Hierarchy to show Versions");
            return false;
        }
        else {

            //debugger;            
            var selrow = jQuery("#dtHier").getRowData(hier_id);
            hier_name = jQuery("#dtHier").getRowData(hier_id)['HIER_NAME'];
            var url = "ConfigHierCallback.aspx?operation=get_VersionData&hier_id=" + hier_id;

            $.ajax({
                async: true,
                type: 'GET',
                url: "ConfigHierCallback.aspx?operation=get_VersionColumns&hier_id=" + hier_id,
                data: "",
                success: function (result) {
                    //debugger;
                    $("#dtVer").GridUnload(); // destroy the grid saving the table and pager
                    var editurl = "table=X_HIER_VERSIONS&hier_id=" + hier_id;

                    fillgridHierNav(eval('(' + result + ')'), "#dtVer", "#pgVer", "800", "350px", "Versions for " + hier_name, editurl, url);
                },
                error: function (x, e) {
                    ////debugger;
                    alert(x.readyState + " " + x.status + " " + e.msg);
                }
            });


        }
    }
}


//end of hierarchy sub-tab

//-----------------------------------------
// start of node type

function submitNodeClick() {
    //debugger;
    //$('#TreeNode').jstree('refresh', -1);
    table_name = $("#Cdrp_hier option:selected").data("TableName");
    hier_id = $("#Cdrp_hier").val();
    vers_id = $("#Cdrp_ver").val();
    is_published = $("#Cdrp_ver option:selected").data("IS_PUBLISHED");

    //validation 
    var bvalidmsg = validationOnSubmit(hier_id, vers_id);
    if (bvalidmsg != "") { alert(bvalidmsg); return false; }

    if ($("#TreeNode").children().length === 0) {
        BindTreeNode(true);
    }
    else {
        $.get('ConfigHierCallback.aspx?reconstruct=1', function () {
            //debugger;
            $('#TreeNode').children().remove().end();
            BindTreeNode(true);
        });
    }

    //clear grid data
    $("#dtNodeType").jqGrid("clearGridData", true);
}

//validation on submit for date and hier and ver selection
function validationOnSubmit(hier_id, ver_id) {
    //////debugger;
    var msg = "";
    if ($.trim(hier_id) == "") { msg = "Please select hierarchy"; return msg; }
    if ($.trim(ver_id) == "") { msg = "Please select version"; return msg; }

    return msg;

}


function BindTreeNode(root_flag) {
    // debugger;
    isNodeType = true;

    $("#TreeNode")
	.jstree({
	    // List of active plugins
	    "plugins": [
	        "themes", "json_data", "ui", "crrm", "dnd", "search", "types", "hotkeys", "contextmenu"
		],
	    // I usually configure the plugin that handles the data first
	    // This example uses JSON as it is most common
	    "json_data": {
	        // This tree is ajax enabled - as this is most common, and maybe a bit more complex
	        // All the options are almost the same as jQuery's AJAX (read the docs)
	        "ajax": {
	            // the URL to fetch the data
	            "url": "ConfigHierCallback.aspx", //+ urlParams,
	            // the `data` function is executed in the instance's scope
	            // the parameter is the node being loaded 
	            // (may be -1, 0, or undefined when loading the root nodes)
	            "data": function (n) {
	                // debugger;
	                // the result is fed to the AJAX request `data` option
	                return {
	                    "operation": "get_children",
	                    "id": n.attr ? n.attr("id").replace("node_", "") : "",
	                    "table_name": $("#Cdrp_hier option:selected").data("TableName"),
	                    "hier_id": hier_id,
	                    "vers_id": vers_id,
	                    "root_flag": root_flag
	                };
	            }
	        }
	    },

	    "contextmenu": { "items": customMenuN },

	    // Configuring the search plugin
	    "search": {
	        // As this has been a common question - async search
	        // Same as above - the `ajax` config option is actually jQuery's AJAX object
	        "ajax": {
	            "url": "ConfigHierCallback.aspx",
	            // You get the search string as a parameter
	            "data": function (str) {
	                return {
	                    "operation": "search",
	                    "search_str": str
	                };
	            }
	        }
	    },

	    // Using types - most of the time this is an overkill
	    // read the docs carefully to decide whether you need types
	    "types": {
	        // I set both options to -2, as I do not need depth and children count checking
	        // Those two checks may slow jstree a lot, so use only when needed
	        "max_depth": -2,
	        "max_children": -2,
	        // I want only `drive` nodes to be root nodes 
	        // This will prevent moving or creating any other type as a root node
	        "valid_children": ["folder"],
	        "types": {
	            // The default type
	            "default": {
	                // I want this type to have no children (so only leaf nodes)
	                // In my case - those are files
	                "valid_children": "none",
	                // If we specify an icon for the default type it WILL OVERRIDE the theme icons
	                "icon": {
	                    "image": "../Images/file.png"
	                }
	            },
	            // The `folder` type
	            "folder": {
	                // can have files and other folders inside of it, but NOT `drive` nodes
	                "valid_children": ["default", "folder"],
	                "icon": {
	                    "image": "../Images/folder.png"
	                }
	            }
	        }
	    },
	    // UI & core - the nodes to initially select and open will be overwritten by the cookie plugin


	    // the UI plugin - it handles selecting/deselecting/hovering nodes
	    "ui": {
	    // this makes the node with ID node_4 selected onload
	    //"initially_select" : [ "node_4" ]
	},
	// the core plugin - not many options here
	"core": {
	// just open those two nodes up
	// as this is an AJAX enabled tree, both will be downloaded from the server
	// "initially_open" : [ "node_2" , "node_3" ] 
},

"crrm": {
    "move": {
        "check_move": function (data) {
            ////debugger;
            return false;
        }
    }
}

})


    // My Defined Functions starts
    .bind("before.jstree", function (e, data) {
        if (data.func === "open_node") {
            root_flag = false;
        }

        if (data.func === "show_contextmenu") {
            root_flag = false;
        }

        if (data.plugin === "types") {
            //////debugger;
            //root_flag = false;
        }

        //remove confirmation
        if (data.func === "remove") {

            var nodename = $.trim(data.args[0].children("a").text());
            var isleaf = $.trim(data.args[0].attr('isleaf'));

            if (isleaf == "0") {
                alert("Cannot delete ! all child nodes either should be inactivated or moved to different node !");
                e.stopImmediatePropagation();
                return false;
            }
            else {
                if (data.func === "remove" && !confirm("Are you sure you want to delete " + nodename + " ?")) {
                    e.stopImmediatePropagation();
                    return false;
                }
            }
        }

        // move confirmation
        if (data.func == "move_node" && data.args[1] == false && data.plugin == "core" && data.args[0].o != undefined) {
            ////debugger;
//            var optval = $("input[name='sdate']:checked").val();
//            if (optval != 'todate') {
//                e.stopImmediatePropagation();
//                return false;
//            }

//            //alert($(".jstree-invalid").length); 
//            if ($(".jstree-invalid").length == 0) { //check with naval
//                ////debugger;
//                nodename = $.trim(data.args[0].o.children("a").text());
//                var destparent = $.trim(data.args[0].np.children("a").text());
//                var orgparent = $.trim(data.args[0].op.children("a").text());
//                var msg;
//                if (destparent == orgparent) {
//                    msg = "Are you sure you want to change order ?";
//                }
//                else {
//                    msg = "Are you sure you want to move '" + nodename + "' to '" + destparent + "' ?";
//                }

//                //if (confirm("Are you sure you want to move '" + nodename + "' to '" + destparent + "' ?") === false) {
//                if (confirm(msg) === false) {
//                    e.stopImmediatePropagation();
//                    return false;
//                }

//                ////debugger;
//                var msgRel = false;
//                msgRel = "Do you want to move the related data ?";
//                if (confirm(msgRel) === true) {
//                    bmoveRelflag = true;
//                }
//            }
        }
    })

    //remove tree fuction
	.bind("remove.jstree", function (e, data) {
	    data.rslt.obj.each(function () {

	        $.ajax({
	            async: true,
	            type: 'POST',
	            url: "ConfigHierCallback.aspx?operation=remove_nodetype&id=" + $(data.rslt.obj).attr("id") + "&hier_id=" + hier_id + "&vers_id=" + vers_id,
	            success: function (r) {
	                if (r == "false") {
	                    $.jstree.rollback(data.rlbk);
	                    alert("Cannot delete !");
	                    return false;
	                }
	                else if (r == "true") {
	                    alert("removed sucessfully !");
	                }
	            }
	        });
	    });
	})


    //funstion for select node 
	.bind("select_node.jstree", function (e, data) {
	    //debugger;
	    node_type_id = $(data.rslt.obj).attr("id");

	    //get attribute of that node type
	    getAttrN();

	})

	.bind("open_node.jstree", function (e, data) {
	    ////debugger;
	    var insIcon = $("jstree-focused a ins.jstree-icon");
	    var liIcon = $("jstree-focused li");

	    $(data.args[0]).find("[ownparent='true']").children("a").append("<strong style='color:red' >*</strong>")
	})

    //function for rename 
	.bind("rename.jstree", function (e, data) {
	    //debugger;
	    //var node_type_id = $(data.rslt.obj).attr("id");
	    //var hier_id = $("#Cdrp_hier").val();
	    //var vers_id = $("#Cdrp_ver").val();

	    $.ajax({
	        async: true,
	        type: 'POST',
	        url: "ConfigHierCallback.aspx?operation=rename_nodetype&id=" + $(data.rslt.obj).attr("id") + "&new_name=" + data.rslt.new_name + "&hier_id=" + hier_id + "&vers_id=" + vers_id,
	        success: function (str) {
	            //$.jstree.rollback(data.rlbk);
	        }
	    });
	})

    //    .bind('load_node.jstree', function (e, data) {
    //        //debugger;
    //        var $nodes = data.rslt.obj;
    //        if ($nodes == -1) {
    //            // Loaded the root node, however jstree doesn't tell us
    //            // what the nodes are. We have to find them ourselves.
    //            $nodes = $('#tree').find('ul:first-child > li');
    //            // data.inst._get_children(data.rslt.obj)
    //            //This way you will always get the new nodes that were inserted.
    //        }
    //        //....
    //    })

    //function for move node
	.bind("move_node.jstree", function (e, data) {
	    // //debugger;
	    //var selected_ind = $tabs.tabs('option', 'selected'); // => index of tab
	    //var dimtabName = $('#tabsDim a')[selected_ind].hash;
	    // alert(dimtabName);

	    data.rslt.o.each(function (i) {
	        $.ajax({
	            async: true,
	            type: 'POST',
	            url: "Callback.aspx?operation=move_node&id=" + $(this).attr("id") + "&table_name=" + table_name + "&vers_id=" + vers_id + "&hier_id=" + hier_id + "&copy=" + data.rslt.cy + "&refid=" + data.rslt.np.attr("id") + "&txtdate=" + $('#txt_date').val() + "&type_id=" + $(this).attr("typeid") + "&bmoveRelflag=" + bmoveRelflag,
	            success: function (r) {
	                //debugger;

	                if (r == "false") {
	                    $.jstree.rollback(data.rlbk);
	                    alert("Can't move to this parent !");
	                    return false;
	                }
	                else {

	                    var totid = r.split(";");
	                    var movedid = 0;
	                    var i;

	                    for (i = 0; i < totid.length - 1; i++) {
	                        var newoldid = totid[i].split(",");
	                        $("#" + newoldid[0]).attr('id', newoldid[1]);

	                        if (i == 0) { movedid = newoldid[1]; }

	                    }

	                    //alert("moved successfully !");
	                    //refresh all exist grid
	                    if (bmoveRelflag == false) {

	                        var dimname;

	                        //node_id = $(data.rslt.obj).attr("id");
	                        node_id = movedid;

	                        if (node_id == undefined) { node_id = 0; }

	                        for (i = $('#tabsDim').tabs('length') - 1; i > 0; i--) {

	                            dimname = $('#tabsDim a')[i].hash;
	                            dimname = dimname.replace('#', '');

	                            var tblnameEx = "#dtgrid" + dimname + "ex";
	                            var pgnameEx = "#pg" + dimname + "ex";
	                            var opr = "get_griddata";
	                            var url = "Callback.aspx?operation=" + opr + "&table_name=" + table_name + "&dimname=" + dimname + "&hier_id=" + hier_id + "&node_id=" + node_id + "&txtdate=" + $('#txt_date').val();

	                            refreshgrid("griddata.gridEx", tblnameEx, url);
	                        }
	                        ///
	                    }
	                }
	            }

	        });
	    });
	});

    //for node type 
    isNodeType = false;
}


//custom menu
function customMenuN(node) {

    //debugger;
    var items;
    var bflag = false;

    if (is_published == true) {
        bflag = true;
    }

    // The default set of all items
    items = { // Could be a function that should return an object like this one
        "create": {
            "separator_before": false,
            "separator_after": true,
            "label": "Add Child Node Type", // Change Naval 
            "_disabled": bflag,     // clicking the item won't do a thing 
            "action": function (obj) { showCreateOptionsN(obj); }
        },
        "rename": {
            "separator_before": false,
            "separator_after": true,
            "label": "Rename",
            "action": function (obj) { this.rename(obj); }
        },
        "remove": {
            "separator_before": false,
            "icon": false,
            "separator_after": true,
            "label": "Delete",
            "_disabled": bflag,     // clicking the item won't do a thing 
            "action": function (obj) { if (this.is_selected(obj)) { this.remove(); } else { this.remove(obj); } }
        }
    }

    return items;
}


//on click of add child node add dialog option
function showCreateOptionsN(obj) {

    //debugger;
    //selected_node = this._get_node(obj, true);
    selected_node = $.jstree._focused()._get_node(obj);
    var id = $(selected_node).attr("id");
    var type_id = $(selected_node).attr("typeid");
    var table_name = $("#Cdrp_hier option:selected").data("TableName");
    //var hier_id = $("#Cdrp_hier").val();
    //var vers_id = $("#Cdrp_ver").val();

    var DialogOptions = "Center=Yes; Scrollbar=No; dialogWidth=400px; dialogTop=250px; dialogHeight=250px; Help=No; Status=No; Resizable=No;";
    var OpenUrl = "CreateNodeType.aspx?id=" + id + "&type_id=" + type_id + "&hier_id=" + hier_id + "&vers_id=" + $("#Cdrp_ver").val() + "&table_name=" + table_name;
    var ret = window.showModalDialog(OpenUrl, "Yes", DialogOptions);

    //debugger;

    if (typeof (ret) != "undefined" && ret != "duplicate") {
        //debugger;
        node_vals = eval('(' + ret + ')');
        var new_type_id = $("#" + node_vals.NodeType).attr("typeid");
        createnodeN(obj);
    }
    else {

        alert("Node Type Name already exists !");
        return false;
    }
}

//after closing create-dialog creates node in UI and add in database
function createnodeN(obj) {

    //debugger;
    selected_node = $.jstree._focused()._get_node(obj);
    var id = $(selected_node).attr("id");
    var retval;

    var is_leaf = "1";
    var isOwnParent = false;

    if (node_vals.IsOwnParent == "true") { isOwnParent = true; }
    var ident = node_vals.ident;

    var objnode = { attr: { id: ident, rel: node_vals.NodeName, typeid: ident, isleaf: is_leaf, ownparent: isOwnParent }, data: node_vals.NodeName };
    var tree = jQuery.jstree._focused();

    //temp solution for double creation of node //ask to naval 22-11-2011
    $("#TreeNode").jstree("open_node", $("#" + id));

    tree.create(selected_node, 'inside', objnode, function () { }, true, true);

    // debugger;
    //make is_leaf =0 
    $(selected_node).attr("isleaf", "0");
    $('#TreeNode').jstree("select_node", '#' + ident);
    $('#TreeNode').jstree("deselect_node", '#' + id);

    //debugger;   
    //append red star if it's own parent    
    $("#" + ident + "[ownparent='true']", "#TreeNode").children("a").append("<strong style='color:red' >*</strong>");

    var imageName = node_vals.image;
    //debugger;
    if (imageName != "" && imageName != null) {
        $("#" + ident, "#TreeNode").children("a").children("ins").css('background-image', 'url("../NodeImages/' + imageName + '")');
    }
}

function customTypes() {
    ////debugger;
    var types = {
        // The default type
        "default": {
            // I want this type to have no children (so only leaf nodes)
            // In my case - those are files
            "valid_children": "none",
            // If we specify an icon for the default type it WILL OVERRIDE the theme icons
            "icon": {
                "image": "../Images/file.png"
            }
        },
        // The `folder` type
        "folder": {
            // can have files and other folders inside of it, but NOT `drive` nodes
            "valid_children": ["default", "folder"],
            "icon": {
                "image": "../Images/folder.png"
            }
        },
        // The `drive` nodes 
        "drive": {
            // can have files and folders inside, but NOT other `drive` nodes
            "valid_children": ["default", "folder"],
            "icon": {
                "image": "../Images/root.png"
            },
            // those prevent the functions with the same name to be used on `drive` nodes
            // internally the `before` event is used
            "start_drag": false,
            "move_node": false,
            "delete_node": false,
            "remove": false
        }
    }
    return types;
}


function ChangeTypes() {
    ////debugger;
    settings = $('#TreeNode').jstree('get_settings');
    settings.types = { 'types': function () {
        // The default type
        var objTypes = {
            "default": {
                // I want this type to have no children (so only leaf nodes)
                // In my case - those are files
                "valid_children": "none",
                // If we specify an icon for the default type it WILL OVERRIDE the theme icons
                "icon": {
                    "image": "../Images/file.png"
                }
            },
            // The `folder` type
            "folder": {
                // can have files and other folders inside of it, but NOT `drive` nodes
                "valid_children": ["default", "folder"],
                "icon": {
                    "image": "../Images/folder.png"
                }
            },
            // The `drive` nodes 
            "drive": {
                // can have files and folders inside, but NOT other `drive` nodes
                "valid_children": ["default", "folder"],
                "icon": {
                    "image": "../Images/root.png"
                },
                // those prevent the functions with the same name to be used on `drive` nodes
                // internally the `before` event is used
                "start_drag": false,
                "move_node": false,
                "delete_node": false,
                "remove": false
            }
        }
        return objTypes;
    }
    }
    $('#TreeNode').jstree('set_settings', settings);
    $('#TreeNode').jstree('refresh', -1);

}


//to ger attribute data
//function getAttr(e, data) {
function getAttrN() {

    //debugger;

    if (tempNodeTypeId[0] != node_type_id) {

        tempNodeTypeId[0] = node_type_id;

        var node_type_name = "";
        var url = "ConfigHierCallback.aspx?operation=get_AttrData&node_type_id=" + node_type_id + "&hier_id=" + hier_id + "&vers_id=" + vers_id;

        $.ajax({
            async: true,
            type: 'GET',
            url: "ConfigHierCallback.aspx?operation=get_AttrColumns",
            data: "",
            success: function (result) {
                // debugger;              

                $("#dtNodeType").GridUnload(); // destroy the grid saving the table and pager
                var editurl = "table=X_NODE_TYPE_ATTR&hier_id=" + hier_id + "&vers_id=" + vers_id + "&node_type_id=" + node_type_id;

                var node_name = $("#" + node_type_id, "#TreeNode").attr("rel");
                fillgridHierNav(eval('(' + result + ')'), "#dtNodeType", "#pgNodeType", "550", "350px", "Attributes for " + node_name, editurl, url);
            },
            error: function (x, e) {
                //debugger;
                alert(x.readyState + " " + x.status + " " + e.msg);
            }
        });
    }
}

//suffice * if mandatory field and add datepicker on add/edit dialog box
function SufficeStarHier(colModelLocal, formid, type) {

    //debugger;

    var appendtag = "<font style='font-weight: bold; color: #FF0000; vertical-align: bottom;'>*</font>";

    for (i = 0, len = colModelLocal.length; i < len; i++) {
        var edtrul = colModelLocal[i].editrules;
        var name = colModelLocal[i].name;
        if (edtrul.date === true) {
            $("#" + name, formid).datepicker();

            //if version grid
            var reccnt = $("#dtVer").getGridParam("reccount") + 1;
            var todate;
            //if (formid.attr("id") == "FrmGrid_dtVer" && type == "new") {
            if (formid.attr("id") == "FrmGrid_dtVer" && type == "new" && (name == "START_DATE" || name == "END_DATE")) {

                if (reccnt == 0) {
                    todate = getCurrDate();
                    $("#" + name, formid).val(todate);
                } else {

                    var enddates = jQuery("#dtVer").jqGrid('getCol', 'END_DATE', false, '');
                    var maxDate = Getmaxdate(enddates);
                    //$("#" + name, formid).val(todate);
                    var newDate = new Date(maxDate.getFullYear(), maxDate.getMonth(), maxDate.getDate() + 1);
                    // now extract the bits we want to crete the text version of the new date..
                    var newDateString = ('0' + (newDate.getMonth() + 1)).substr(-2) + '/' + ('0' + newDate.getDate()).substr(-2) + '/' + newDate.getFullYear();

                    $("#" + name, formid).datepicker('option', { minDate: new Date(newDateString) });
                }
            }
            else {
                todate = getCurrDate();
                $("#" + name, formid).val(todate);
            }
            //
        }
        if (edtrul.required === true) {
            var relTo = $("#" + name, formid);
            $(appendtag).insertAfter(relTo);
        }
    }
}

//get maxdate and add 1
function Getmaxdate(arrdate) {
    //debugger;

    var dates = [];

    for (var i = 0; i < arrdate.length; i++) {
        var arrdata = arrdate[i].split('/');
        dates.push(new Date(arrdata[2] + "/" + arrdata[0] + "/" + arrdata[1]));
    }

    var maxDate = new Date(Math.max.apply(null, dates));
    // convert back to date object
    maxDate = new Date(maxDate);

    // var newDate = new Date(maxDate.getFullYear(), maxDate.getMonth(), maxDate.getDate() + 1);
    // now extract the bits we want to crete the text version of the new date..
    // var newDateString = ('0' + (newDate.getMonth()+1)).substr(-2) + '/' + ('0' + newDate.getDate()).substr(-2) + '/' + newDate.getFullYear();

    return maxDate;
}

//publish a hierarchy
function publishClick() {

    // debugger;
    hier_id = $("#Cdrp_hier").val();
    vers_id = $("#Cdrp_ver").val();
    var url = "ConfigHierCallback.aspx?operation=publishHierarchy&hier_id=" + hier_id + "&vers_id=" + vers_id;

    $.ajax({
        async: true,
        type: 'POST',
        url: url,
        data: "",
        dataType: "json",
        success: function (result) {
            //debugger;
            var arr = result.toString().split("|");

            if (arr[0] == "false") {
                if (arr[1] != "") {
                    alert(arr[1]);
                }
            }
            else {
                alert("Published Successfully !");
                //BindVersionCombo("bind_version", hier_id, "Cdrp_ver", "hier");
                $("#Cdrp_ver option:selected").data("IS_PUBLISHED", true);
                $("#submitPublish").attr("disabled", "disabled");
                is_published = true;
                return false;
            }
        },
        error: function (x, e) {
            //debugger
            alert(x.readyState + " " + x.status + " " + e.msg);
        }
    });
}

